package gss.generator;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

import org.apache.commons.math.fraction.BigFraction;

import gss.LineSegment;
import gss.Vertex;
import static gss.generator.GeneratorUtils.*;

public class VertexGenerator {
    /** A collection of LineSegments */
    private static List<LineSegment> linesegs =
	new ArrayList<LineSegment>();
    private static List<Vertex> endpoints = new ArrayList<Vertex>();
    private static List<Vertex> intersections = new ArrayList<Vertex>();

    private static int segnum = 100;
    private static int gridsize = segnum;

    private static double probVertexToVertex = .5;
    //private static double probVertexToRandom = .5;
    
    // output file names
    private static String gssFile;
    private static String matrixFile;
    private static String vertexFile;
    
    public static void main(String[] args) {
	// parse command line arguments (6):
	//   segnum gridsize
	//   probVertexToVertex
	//   gssFile matrixFile vertexFile
	if (args.length < 6) {
	    System.err.println("Incorrect number of arguments.");
	    System.err.println(
		    "Arguments: segnum gridsize probVertexToVertex" + 
		    " gssFile matrixFile intersectionFile");
	    System.exit(1);
	} else {
	    segnum = Integer.parseInt(args[0]);
	    gridsize = Integer.parseInt(args[1]);
	    probVertexToVertex = Double.parseDouble(args[2]);
	    if (probVertexToVertex > 1) {
		System.err.println("probability must be <= 1");
		System.exit(1);
	    }
	    gssFile = args[3];
	    matrixFile = args[4];
	    vertexFile = args[5];
	}
	
	//create first line segment
	addSegmentEndpointsAndIntersections(randomSegment(gridsize),
		linesegs, endpoints, intersections);
	
	//generate all line segments
	for(int i = 1; linesegs.size() < segnum; i++){
	    if(Math.random() <= probVertexToVertex){
		LineSegment seg = vertexToVertex(endpoints, linesegs);
		    if(seg != null){
			addSegmentEndpointsAndIntersections(
				seg, linesegs, endpoints, intersections);
		    }
		    else{
			addSegmentEndpointsAndIntersections(
				randomVertexToRandom(
					endpoints, linesegs, gridsize),
				linesegs, endpoints, intersections);
		    }
	    }
	    else{
		addSegmentEndpointsAndIntersections(
			randomVertexToRandom(endpoints, linesegs, gridsize),
			linesegs, endpoints, intersections);
	    }
	}
	  
	 /* 
	  //find all intersection points
	  // not needed b/c of addSegment
	  for (LineSegment seg1 : linesegs) {
	      for(LineSegment seg2 : linesegs)
		if (!seg1.equals(seg2) && seg1.intersects(seg2)) {
		    addVertex(seg1.intersectionPoint(seg2), intersections);
		}
	  }
	  */
	  
	  //uncomment to print out all of the line segments
	 /* for(LineSegment seg : linesegs){
	      System.err.println(seg);
	  }
	  System.err.println("number of endpoints used =  " +
		  endpoints.size());
	  */
	  
	writeFiles(linesegs, intersections,
		gssFile, matrixFile, vertexFile);

    }//end main

}
